﻿using Microsoft.Extensions.Options;
using System;
using System.Security.Cryptography;
using System.Text;
using Tiens.NotificationHub.Core.Options;

namespace Tiens.NotificationHub.Core.Utils
{
    public class CBCDecryptor
    {
        private readonly CBCOptions _options;

        public CBCDecryptor(IOptions<CBCOptions> options)
        {
            _options = options.Value;
        }

        public bool TryDecrypt(string ciphertext, out string content)
        {
            var success = true;
            content = "";
            try
            {
                var keyBytes = Encoding.UTF8.GetBytes(_options.Key);
                var textBytes = Convert.FromBase64String(ciphertext);
                var ivBytes = Encoding.UTF8.GetBytes(_options.IV);

                var aes = Aes.Create();
                aes.KeySize = 256;
                aes.BlockSize = 128;
                aes.Padding = PaddingMode.PKCS7; //填充模式
                aes.Mode = CipherMode.CBC;
                aes.Key = keyBytes;
                aes.IV = ivBytes;

                var cryptoTransform = aes.CreateDecryptor();
                var resultBytes = cryptoTransform.TransformFinalBlock(textBytes, 0, textBytes.Length);
                content = Encoding.UTF8.GetString(resultBytes);
            }
            catch (Exception)
            {
                success = false;
            }

            return success;
        }
    }
}
